<?php

function tbnd_login_google_login_validate($google_user) {
    global $language, $user;
    /*----------get_email_from_google------------*/
    $email = $google_user['openid_ext1_value_email'];
    /*----------get_email_from_google------------*/
    
    /*----------check_mail_in_system_thubannhadat.vn_------------*/
    $uid = api_get_uid_by_email($email); 
    /*----------check_mail_in_system_thubannhadat.vn_------------*/
    
    if ($uid != NULL) { //nếu tài khoản đã đăng kí
        $form_state['uid'] = $uid;
        user_login_submit(array(), $form_state);
        return $uid;
    } else {////nếu tài khoản chưa đăng kí
        define('DRUPAL_ROOT', getcwd());
        require_once  DRUPAL_ROOT . '/includes/bootstrap.inc';
        drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
        require_once  DRUPAL_ROOT . '/includes/password.inc';
        
        /*-----create_password_radom-----------------------------------------------*/
        $pass = substr(str_shuffle(str_repeat("0123456789abcdefghijklmnopqrstuvwxyz", 6)), 0, 6);
        /*-----create_password_radom-----------------------------------------------*/
        /*-----------save_account_--------------------*/
        $data = (object) array(
                'name' => $google_user['openid_ext1_value_email'] , // ? time() : $username,
                'pass' => user_hash_password( $pass ),
                'mail' => $google_user['openid_ext1_value_email'],
                'init' => $google_user['openid_ext1_value_email'],
                'status' => ACTIVED,
                'timezone' => 'Asia/Ho_Chi_Minh'
        );       
        //save_account_user
        $account = user_save($data);
        /*-----------save_account_--------------------*/
        
        if($account){//nếu save user thành công
            /*-----------save_account_config_thuebannhadat.vn--------------------*/
            $user_oauth = array(
                'uid'                       => $account->uid , 
                'txt_signup_fullname'       => trim($google_user['openid_ext1_value_firstname'] . ' ' . $google_user['openid_ext1_value_lastname']),
                'txt_signup_address'        => '',
                'txt_signup_phone'          => '',                
            );
            tbnd_save_user( $user_oauth );    
            /*-----------save_account_config_thuebannhadat.vn--------------------*/
            //load_user_
            $user = user_load($account->uid);
            user_login_finalize();
            $json['status'] = TRUE;
            /*-----------------------------//save_auth_user_------------------------------*/
            $key_oauth = user_password(128);
            $data->key = $key_oauth;
            $data->pass = $pass;
            $data->fname = trim($google_user['openid_ext1_value_firstname'] . ' ' . $google_user['openid_ext1_value_lastname']) ;
            tbnd_save_oauth_user($google_user['openid_ext1_value_email'] ,  $account->uid ,  $key_oauth , CREATE_ACCOUNT , ACTIVED , REQUEST_TIME);             
            /*--------------------------------------------------------------*/
            
            /*-----------------send_email_active_user-----------------------*/
             //----------------send_mail_to_user----------------------------*/
            $params['subject'] = 'Thông tin tài khoản tại thuebannhadat.vn';
            $params['body'] = theme('email_info_account_register_social', array('info' => $data));
            $send_mail = drupal_mail('tbnd_login', 'send-mail', $google_user['openid_ext1_value_email'] , $language, $params);
            /*-----------------------------------------------------------------*/                           
         }
        else{
            $json['status'] = FALSE;            
        }           
        // send mail      
        return $account->uid;     
    }
}

function tbnd_login_facebook_login_validate($fb_user) {
	global $language, $user;
    $email = $fb_user['email'];
    $uid = api_get_uid_by_email($email); 
    if ($uid != NULL) {
        $form_state['uid'] = $uid;
        user_login_submit(array(), $form_state);
        return $uid;
    } else if($fb_user['email']){
        define('DRUPAL_ROOT', getcwd());
        require_once  DRUPAL_ROOT . '/includes/bootstrap.inc';
        drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
        require_once  DRUPAL_ROOT . '/includes/password.inc';
        /*-----create_password_radom-----------------------------------------------*/
        $pass = substr(str_shuffle(str_repeat("0123456789abcdefghijklmnopqrstuvwxyz", 6)), 0, 6);
        /*-----create_password_radom-----------------------------------------------*/
        
        /*-----------save_account_config_thuebannhadat.vn--------------------*/
        $data = (object) array(
                'name' => $fb_user['email'] , // ? time() : $username,
                'pass' => user_hash_password( $pass ),
                'mail' => $fb_user['email'],
                'init' => $fb_user['email'],
                'status' => ACTIVED,
                'timezone' => 'Asia/Ho_Chi_Minh'
        );       
        $account = user_save($data);			
        /*-----------save_account_config_thuebannhadat.vn--------------------*/
        
         if($account){
             /*-----------save_account_config_thuebannhadat.vn--------------------*/
            $user_oauth = array(
                'uid'                       => $account->uid , 
                'txt_signup_fullname'       => trim( $fb_user['name'] ),
                'txt_signup_address'        => $fb_user['hometown']['name'] ? $fb_user['hometown']['name'] : '',
                'txt_signup_phone'          => '',                
            );
            tbnd_save_user( $user_oauth );         
            /*-----------save_account_config_thuebannhadat.vn--------------------*/
            
            /*----------load_user_-----------------------------------------------*/
            $user = user_load($account->uid);
            user_login_finalize();
            $json['status'] = TRUE;
            /*----------load_user_-----------------------------------------------*/
            
             /*-----------------------------//save_auth_user_------------------------------*/
            $key_oauth = user_password(128);
            $data->key = $key_oauth;
            $data->pass = $pass;
            $data->fname =  trim( $fb_user['name'] ) ;
            tbnd_save_oauth_user($fb_user['email']  , $account->uid ,  $key_oauth , CREATE_ACCOUNT , ACTIVED , REQUEST_TIME);             
            /*--------------------------------------------------------------*/
            
            /*-----------------send_email_active_user-----------------------*/
             // send mail
            $params['subject'] = 'Thông tin tài khoản tại thuebannhadat.vn';
            $params['body'] = theme('email_info_account_register_social', array('info' => $data));
            $send_mail = drupal_mail('tbnd_login', 'send-mail', $fb_user['email'] , $language, $params);
            /*-----------------------------------------------------------------*/            
            // user_login_submit(array(), $form_state);
            ///$_SESSION['user_oauth'] = $user_oauth;                         
         }
        else{
            $json['status'] = FALSE;            
        }           
        // send mail      
        return $account->uid;     
    }
}

function active_code_user(){
    $key = arg(1);
    $account = db_query("SELECT * FROM tbnd_user_oauth WHERE oauth_id = :oauth_id AND type_oauth = 5 AND  status = 0", array(':oauth_id' => $key))->fetchObject();
    if($account){
        db_update('users')
        ->fields(array(                        
                'status'  =>  ACTIVED , 
            ))
            ->condition('uid', $account->uid)
            ->execute();
         db_update('tbnd_user_oauth')
        ->fields(array(                        
                'status'  =>  ACTIVED , 
                'time_oauth'  =>  REQUEST_TIME , 
            ))
            ->condition('uid', $account->uid)
            ->execute();
        $data['status'] = true;        
    }
    else{
         $data['status'] = false;
    }
    return theme('report_status_active_user' , $data);
}

function active_recover_pass_user(){
	$email = $_REQUEST['email'];
	$key = $_REQUEST['key'];
	$check_key = db_query("SELECT * FROM tbnd_user_oauth WHERE email = :email AND oauth_id = :oauth_id AND type_oauth = :type_oauth", array('email' => $email, ':oauth_id' => $key , 'type_oauth' => RECOVER_PASSWORD))->fetchObject();
	if($check_key && !user_is_logged_in()){
		 global $user;
		//add_css
		drupal_add_css(drupal_get_path('module', 'tbreal') . '/assets/css/manager_account.css');
		//drupal_add_css(drupal_get_path('module', 'tbnd_system') . '/assets/css/manager_account.css');		
		//drupal_add_css(drupal_get_path('module', 'tbnd_plugin') . '/upload/css/custom_fileuploader.css');
		//add_js		
		drupal_add_js(drupal_get_path('module', 'tbnd_system') . '/assets/js/update_info_system.js');
		
		$data['email'] = $email;
		return theme('recover_password' , $data);
	}
	drupal_goto();
}
